<template>
  <div class="container">
    <div class="mask" v-if="videoState == true">
      <div class="close" @click="Close">
        <span class="el-icon-close"></span>
      </div>
      <div class="videomasks" v-if="videoState == true">
        >
        <video :src="videoURL"></video>
      </div>
    </div>
    <el-card>
      <el-row>
        <el-col :span="21">
          <el-form :inline="true" :model="list">
            <el-form-item label="关键字" prop="keyword">
              <el-input v-model="list.keyword"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <el-select v-model="list.state">
                <el-option
                  v-for="item in status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="hClear">清除</el-button>
              <el-button type="primary" @click="hSearch">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <el-col :span="3">
          <el-button type="success" @click="hAdd"
            ><i class="el-icon-edit"></i>新增技巧</el-button
          >
        </el-col>
      </el-row>
      <el-alert
        :title="`数据一共${total}条`"
        type="info"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-table :data="dataList">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column prop="title" label="文章标题" width="400px">
          <template v-slot="scope">
            {{ scope.row.title }}

            <el-button
              type="text"
              v-if="scope.row.videoURL"
              class="el-icon-film"
              @click="hVideo(scope.row.id, scope.row.videoURL)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="visits"
          label="阅读数"
          width="140px"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="录入人"
          width="140px"
        ></el-table-column>
        <el-table-column prop="createTime" label="录入时间">
          <template v-slot="scope">
            {{ shijianc(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100px">
          <template v-slot="scope"
            >{{ formatStatus(scope.row.state) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <el-button type="text" @click="hPreview(scope.row.id)"
              >预览</el-button
            >
            <el-button
              type="text"
              @click="hState(scope.row.id, scope.row.state)"
              >{{ formatSta(scope.row.state) }}
            </el-button>
            <el-button
              type="text"
              :disabled="scope.row.state === 1 ? true : false"
              @click="hEdit(scope.row.id)"
              >修改</el-button
            >
            <el-button
              type="text"
              :disabled="scope.row.state === 1 ? true : false"
              @click="hdel(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row style="text-align: right">
        <el-pagination
          v-if="total > 10"
          background
          layout=" prev, pager, next, sizes, jumper"
          :page-sizes="[2, 5, 10]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-row>

      <!-- 外层的遮罩 v-if用来控制显示隐藏 点击事件用来关闭弹窗 -->
      <!-- <div class="mask" v-if="videoState == true"></div> -->
      <!-- 弹窗 -->

      <!-- <div class="videomasks" v-if="videoState == true"> -->
      <!-- 视频：h5的视频播放video -->
      <!-- <video :src="videoURL" width="800px" height="600px"></video> -->
      <!-- </div> -->
    </el-card>

    <el-dialog
      @close="hClose"
      :title="isEdit ? '修改文章' : '添加文章'"
      :visible.sync="showDialog"
      width="800px"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input
            placeholder="请输入文章标签"
            v-model="formData.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="articleBody">
          <quill-editor
            :options="editorOption"
            style="height: 200px"
            v-model="formData.articleBody"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址" prop="videoURL">
          <el-input
            placeholder="请输入视频地址"
            v-model="formData.videoURL"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="hClose">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      class="preview"
      title="预览文章"
      :visible.sync="showDialog2"
      width="800px"
    >
      <div>
        <h2>{{ detail.title }}</h2>
        <span>{{ shijianc(detail.createTime) }}</span>
        <span> {{ username }}</span>
        <span><i class="el-icon-view"></i></span>
        <span>{{ detail.visits }}</span>
      </div>
      <div class="content" v-html="detail.articleBody"></div>
    </el-dialog>
  </div>
</template>

<script>
// 导入富文本编辑器
import VueQuillEditor from "vue-quill-editor";
// 导入富文本编辑器的样式
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
//导入vue(在main.js中这行可以省略。 )
import Vue from "vue";
// 全局注册富文本编辑器
Vue.use(VueQuillEditor);

import {
  list,
  remove,
  add,
  changeState,
  simple,
  update,
  detail,
  getUser,
} from "@/api/hmmm/articles.js";
import { status } from "@/api//hmmm/constants.js";

const res = status.reduce((sum, item) => {
  sum[item.value] = item.label;
  return sum;
}, {});
// console.log(res, Object.keys(res)[0]);

export default {
  data() {
    return {
      formData: {
        title: "",
        articleBody: "",
        videoURL: "",
        id: "",
      },
      formRules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        articleBody: [{ required: true, message: "请输入文章内容" }],
      },
      dataList: [],
      detail: {
        creatorID: "",
      },
      username: "",
      list: {
        page: 1,
        pagesize: 10,
        keyword: "",
        state: null,
      },

      total: 0,
      status,
      showDialog: false,
      isEdit: false,
      showDialog2: false,
      videoURL: "",
      videoState: false,
      // 富文本编辑器配置
      editorOption: {
        // 编辑器配置
        placeholder: "请在这里输入",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            [{ list: "ordered" }, { list: "bullet" }], //列表
            ["blockquote"], //引用，代码块
            ["code-block", "link", "image"], // ["link", "image", "video"], //上传图片、上传视频
            // [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            // [{ script: "sub" }, { script: "super" }], // 上下标
            // [{ indent: "-1" }, { indent: "+1" }], // 缩进
            // [{ direction: "ltl" }], // 文本方向
            // [{ direction: "rtl" }], // 文本方向
            // [{ size: ["small", false, "large", "huge"] }], // 字体大小
            // [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
            // [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            // [{ font: [] }], //字体
            // [{ align: [] }], //对齐方式
            // ["clean"], //清除字体样式
          ],
        },
      },
    };
  },

  created() {
    this.loadList();
  },
  methods: {
    checkVideo() {},
    async loadList() {
      try {
        const res = await list({
          page: this.list.page,
          pagesize: this.list.pagesize,
        });
        // console.log(res);
        this.dataList = res.data.items;
        this.total = res.data.counts;
        // const arr = this.dataList.filter((item) => item.state == 1);
        // console.log(arr);
        // arr.forEach((item) => (this.ban = true));
      } catch (err) {
        console.log(err);
      }
    },
    handleSizeChange(val) {
      this.list.pagesize = val;
      this.loadList();
    },
    handleCurrentChange(val) {
      this.list.page = val;
      this.loadList();
      // console.log(this.status);
    },
    formatStatus(state) {
      // console.log(state);
      return "已" + res[state];
    },
    formatSta(state) {
      if (state == 1) {
        return "禁用";
      } else {
        return "启用";
      }
    },
    hdel(id) {
      // console.log(id);
      // console.log(id);
      this.doDel(id);
    },
    doDel(id) {
      this.$confirm("此操作将永久删除该文章, 是否继续?", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      })
        .then(async () => {
          const res = await remove(id);
          // console.log(res);
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.loadList();
        })
        .catch(() => {});
      if (this.dataList.length === 1) {
        let page = this.list.page;
        page--;
        // 页面不能减是0
        // if(this.pageParams.page === 0){
        // this.pageParams.page = 1
        // }
        page = Math.max(1, page);
        this.list.page = page;
      }
    },
    hAdd() {
      this.showDialog = true;
      this.isEdit = false;
    },

    async doAdd() {
      try {
        const res = await add(this.formData);
        console.log(res);
        this.$message.success("添加成功"),
          this.loadList(),
          (this.showDialog = false);
      } catch (err) {
        console.log(err);
      }
    },
    hSubmit() {
      if (this.isEdit) {
        this.doEdit();
      } else {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.doAdd();
          }
        });
      }
    },
    hClose() {
      this.showDialog = false;
      this.formData.title = "";
      this.formData.articleBody = "";
      this.formData.videoURL = "";
    },
    async hState(id, state) {
      if (state == 1) {
        state = 0;
        const res = await changeState(id, state);
        // console.log(res);
        this.loadList();
      } else if (state == 0) {
        this.ban = true;
        state = 1;
        const res = await changeState(id, state);
        // console.log(res);
        this.loadList();
      }
      // if (res.data.success) {
      //   // this.formatSta(state);
      // }
    },
    async hEdit(id) {
      this.isEdit = true;
      this.showDialog = true;
      const res = await detail(id);
      console.log(res);
      this.formData = res.data;
    },
    async doEdit() {
      const res = await update(this.formData);
      console.log(res);
      this.showDialog = false;
      this.loadList();
    },

    async hPreview(id) {
      this.showDialog2 = true;
      const res = await detail(id);
      // console.log(res.data);
      await this.getcreator(res.data.creatorID);
      this.detail = res.data;
    },
    async getcreator(creatorid) {
      const res = await getUser(creatorid);
      // console.log(res);
      this.username = res.data.username;
      // console.log(this.username);
    },
    shijianc(time) {
      var date = new Date(time);
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    async hSearch() {
      const res = await list({
        page: this.list.page,
        pagesize: this.list.pagesize,
        keyword: this.list.keyword,
        state: this.list.state,
      });
      // console.log(res);
      this.dataList = res.data.items;
      this.total = res.data.counts;
    },
    hClear() {
      (this.list.keyword = ""), (this.list.state = null);
    },
    hVideo(id, videoURL) {
      this.videoURL = videoURL;
      //点击按钮出现弹窗播放视频
      this.videoState = true;
      // console.log(videoURL);
    },
    // masksCloseFun() {
    //   this.videoState = false;
    // },
    Close() {
      this.videoState = false;
    },
  },
  // mounted() {
  //   this.$nextTick(() => {
  //     const img = document.querySelector(".content .ql-align-center img");
  //     console.log(img);
  //     // img.style.width = "100%";
  //   });
  // },
};
</script>

<style scoped >
.content {
  background: #f5f5f5;
  padding: 10px;
}
.content > .ql-align-center > img {
  width: 100% !important;
}
.el-icon-film {
  font-size: 18px;
  color: blue;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 10;
  background-color: rgb(0, 0, 0, 0.4);
  /* opacity: 0.2; */
}
.videomasks {
  width: 800px;
  height: 600px;
  position: absolute;
  left: 300px;
  top: 0;
}
video {
  width: 100%;
  height: 100%;
}
.close {
  width: 50px;
  height: 50px;
  position: absolute;
  top: 80px;
  left: 50%;
  transform: translate(-50%);
  background: rgb(0, 0, 0, 0.4);
  box-shadow: 0 0 5px rgb(0 0 0 / 40%);
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
  color: #fff;
  font-size: 20px;
  z-index: 20;
}
</style>
